<template>
  <div class="admin-manage">
    <div class="header">
      <h2>管理员管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        添加管理员
      </el-button>
    </div>

    <!-- 管理员列表 -->
    <el-card>
      <el-table 
        :data="adminList" 
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="adminRole" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.adminRole)">
              {{ getRoleDisplayName(row.adminRole) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 暂时隐藏时间字段，因为数据库表中还没有这些字段 -->
        <!-- <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updatedAt) }}
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="showEditDialog(row)"
              :disabled="row.id === currentAdminId"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="showResetPasswordDialog(row)"
            >
              重置密码
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              :disabled="row.adminRole === 'SUPER_ADMIN' || row.id === currentAdminId"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建管理员对话框 -->
    <el-dialog 
      v-model="createDialogVisible" 
      title="创建管理员" 
      width="500px"
      @closed="resetCreateForm"
    >
      <el-form 
        :model="createForm" 
        :rules="createRules" 
        ref="createFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="createForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="createForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="角色" prop="adminRole">
          <el-select v-model="createForm.adminRole" @change="handleRoleChange">
            <el-option label="普通管理员" value="ADMIN" />
            <el-option label="超级管理员" value="SUPER_ADMIN" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate" :loading="createLoading">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑管理员对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑管理员" 
      width="500px"
      @closed="resetEditForm"
    >
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="角色" prop="adminRole">
          <el-select v-model="editForm.adminRole" @change="handleEditRoleChange">
            <el-option label="普通管理员" value="ADMIN" />
            <el-option label="超级管理员" value="SUPER_ADMIN" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate" :loading="updateLoading">
          更新
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog 
      v-model="resetPasswordDialogVisible" 
      title="重置密码" 
      width="400px"
      @closed="resetPasswordForm"
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="管理员">
          <el-input :value="currentAdmin?.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword" :loading="resetPasswordLoading">
          重置
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import AdminManageService, { type AdminInfo, type AdminCreateRequest, type AdminUpdateRequest } from '@/api/adminManageService'

// 响应式数据
const loading = ref(false)
const adminList = ref<AdminInfo[]>([])
const currentAdminId = ref<number | null>(null)

// 创建管理员相关
const createDialogVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref<FormInstance>()
const createForm = reactive<AdminCreateRequest>({
  username: '',
  password: '',
  adminRole: 'ADMIN',
  adminRoleId: 2
})

// 编辑管理员相关
const editDialogVisible = ref(false)
const updateLoading = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive<AdminUpdateRequest>({
  id: 0,
  username: '',
  adminRole: 'ADMIN',
  adminRoleId: 2
})

// 重置密码相关
const resetPasswordDialogVisible = ref(false)
const resetPasswordLoading = ref(false)
const passwordFormRef = ref<FormInstance>()
const currentAdmin = ref<AdminInfo | null>(null)
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const createRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  adminRole: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const editRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  adminRole: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const passwordRules: FormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 工具函数
const getRoleTagType = (role: string) => {
  return (role === 'SUPER_ADMIN' || role === '超级管理员') ? 'danger' : 'primary'
}

const getRoleDisplayName = (role: string) => {
  if (role === 'SUPER_ADMIN' || role === '超级管理员') {
    return '超级管理员'
  }
  return '普通管理员'
}

const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取管理员列表
const fetchAdminList = async () => {
  loading.value = true
  try {
    const response = await AdminManageService.getAdminList()
    if (response.code === 200) {
      adminList.value = response.data || []
      console.log('📋 [AdminManage] 管理员列表:', adminList.value)
    } else {
      ElMessage.error(response.msg || '获取管理员列表失败')
    }
  } catch (error: any) {
    console.error('❌ [AdminManage] 获取管理员列表失败:', error)
    ElMessage.error(error.response?.data?.msg || '获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  createDialogVisible.value = true
}

// 重置创建表单
const resetCreateForm = () => {
  createForm.username = ''
  createForm.password = ''
  createForm.adminRole = 'ADMIN'
  createForm.adminRoleId = 2
  createFormRef.value?.resetFields()
}

// 处理角色变化
const handleRoleChange = (role: string) => {
  createForm.adminRoleId = role === 'SUPER_ADMIN' ? 1 : 2
}

// 创建管理员
const handleCreate = async () => {
  if (!createFormRef.value) return
  
  const valid = await createFormRef.value.validate().catch(() => false)
  if (!valid) return

  createLoading.value = true
  try {
    const response = await AdminManageService.createAdmin(createForm)
    if (response.code === 200) {
      ElMessage.success('创建管理员成功')
      createDialogVisible.value = false
      fetchAdminList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '创建管理员失败')
    }
  } catch (error: any) {
    console.error('❌ [AdminManage] 创建管理员失败:', error)
    ElMessage.error(error.response?.data?.msg || '创建管理员失败')
  } finally {
    createLoading.value = false
  }
}

// 显示编辑对话框
const showEditDialog = (admin: AdminInfo) => {
  editForm.id = admin.id
  editForm.username = admin.username
  editForm.adminRole = admin.adminRole
  editForm.adminRoleId = admin.adminRoleId
  editDialogVisible.value = true
}

// 重置编辑表单
const resetEditForm = () => {
  editFormRef.value?.resetFields()
}

// 处理编辑角色变化
const handleEditRoleChange = (role: string) => {
  editForm.adminRoleId = role === 'SUPER_ADMIN' ? 1 : 2
}

// 更新管理员信息
const handleUpdate = async () => {
  if (!editFormRef.value) return
  
  const valid = await editFormRef.value.validate().catch(() => false)
  if (!valid) return

  updateLoading.value = true
  try {
    const response = await AdminManageService.updateAdmin(editForm)
    if (response.code === 200) {
      ElMessage.success('更新管理员信息成功')
      editDialogVisible.value = false
      fetchAdminList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '更新管理员信息失败')
    }
  } catch (error: any) {
    console.error('❌ [AdminManage] 更新管理员信息失败:', error)
    ElMessage.error(error.response?.data?.msg || '更新管理员信息失败')
  } finally {
    updateLoading.value = false
  }
}

// 删除管理员
const handleDelete = async (admin: AdminInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除管理员 "${admin.username}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await AdminManageService.deleteAdmin(admin.id)
    if (response.code === 200) {
      ElMessage.success('删除管理员成功')
      fetchAdminList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '删除管理员失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ [AdminManage] 删除管理员失败:', error)
      ElMessage.error(error.response?.data?.msg || '删除管理员失败')
    }
  }
}

// 显示重置密码对话框
const showResetPasswordDialog = (admin: AdminInfo) => {
  currentAdmin.value = admin
  resetPasswordDialogVisible.value = true
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  currentAdmin.value = null
  passwordFormRef.value?.resetFields()
}

// 重置管理员密码
const handleResetPassword = async () => {
  if (!passwordFormRef.value || !currentAdmin.value) return
  
  const valid = await passwordFormRef.value.validate().catch(() => false)
  if (!valid) return

  resetPasswordLoading.value = true
  try {
    const response = await AdminManageService.resetAdminPassword({
      id: currentAdmin.value.id,
      newPassword: passwordForm.newPassword
    })
    if (response.code === 200) {
      ElMessage.success('重置密码成功')
      resetPasswordDialogVisible.value = false
    } else {
      ElMessage.error(response.msg || '重置密码失败')
    }
  } catch (error: any) {
    console.error('❌ [AdminManage] 重置密码失败:', error)
    ElMessage.error(error.response?.data?.msg || '重置密码失败')
  } finally {
    resetPasswordLoading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAdminList()
  
  // 从 authStore 获取当前管理员ID
  const authStore = useAuthStore()
  if (authStore.admin && authStore.admin.username) {
    currentAdminId.value = authStore.admin.adminRoleId || 0
  }
})
</script>

<style scoped>
.admin-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}
</style>
